from datetime import datetime, date
from typing import Optional, Any

import bcrypt
import yaml
from src.base.constants import datetime_pattern, date_pattern


# 读取 yaml 文件
def load_yaml(file_path: str):
    with open(file_path, 'r', encoding='utf-8') as file:
        return yaml.safe_load(file)


# 密码验证
def verify_password(plain_password, hashed_password):
    pwd_bytes = plain_password.encode('utf-8')
    hash_bytes = hashed_password.encode('utf-8')
    try:
        return bcrypt.checkpw(pwd_bytes, hash_bytes)
    except ValueError:  # 处理无效哈希或长度超限
        return False


# 密码加密
def hash_password(password):
    # 生成 salt 并哈希
    pwd_bytes = password.encode('utf-8')
    salt = bcrypt.gensalt(rounds=12)  # 可调整强度
    hashed = bcrypt.hashpw(pwd_bytes, salt)
    return hashed.decode('utf-8')


def to_int(value: Optional[str]) -> Optional[int]:
    return int(value) if value is not None else None


def to_datetime(value: Optional[str]) -> Optional[datetime]:
    return datetime.strptime(value, datetime_pattern) if value is not None else None


def to_date(value: Optional[str]) -> Optional[date]:
    return datetime.strptime(value, date_pattern) if value is not None else None


def to_str(value: Optional[Any]) -> Optional[str]:
    if isinstance(value, datetime):
        return value.strftime(datetime_pattern)
    elif isinstance(value, date):
        return value.strftime(date_pattern)
    elif isinstance(value, int):
        return str(value)
    elif isinstance(value, bool):
        return str(value).lower()
    else:
        return str(value) if value is not None else None
